import { HTTP } from "../../../utils/http"
import api from '../../../utils/api.js'
import { countdownTimer } from "../../../utils/util"
import { config } from '../../../utils/config'

let http = new HTTP()

Page({
  data: {
    imgUrl: config.imgUrl,
    location: {},
    group_list: [],
    current_page: 1,
    last_page: 1,
    interval_handle: null,
  },

  onLoad() {
    // 获取地理位信息
    this.data.location = wx.getStorageSync('address');
    this.data.group_list = [];
    this.data.current_page = 1;
    this.getGroupListForPage(this.data.current_page);
    this.data.interval_handle = setInterval(this.intervalHandle, 1000)
  },

  onShow() {
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.current_page < this.data.last_page) {
      this.data.current_page += 1;
      this.getGroupListForPage(this.data.current_page);
    } else {
      console.log("已经到底了");
    }
  },

  getGroupListForPage(page) {
    let _that = this;
    http.request({
      url: api.groupList,
      method: "get",
      data: {
        page,
        lat: this.data.location.latitude,
        lng: this.data.location.longitude,
      },
      success: function (res) {
        let group_list = _that.data.group_list.concat(res.data.data);
        group_list.forEach(element => {
          element.time = countdownTimer(element.expired_at);
        });
        _that.setData({
          group_list,
          current_page: page,
          last_page: res.data.last_page
        })
      }
    });
  },

  // 计时器
  intervalHandle() {
    this.data.group_list.forEach(element => {
      element.time = countdownTimer(element.expired_at);
    })
    this.setData({ group_list: this.data.group_list })
  },
})